﻿using OneWorks.Utils.Specifications;

namespace OneWorks.Application
{
    using Interface;
    using Metadata.Entity;
    using Repositories.Interface;
    using Repositories.EntityFramework;
    using System;
    using Metadata.Enum;
    using Entity;
    using Newtonsoft.Json;

    public class UserService : BaseService, IUserService
    {
        private readonly IUserRepository _userRepository;

        public UserService()
        {
            _userRepository = new UserRepository(RepositoryContext);
        }

        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public RunResult<User> Add(User user)
        {
            RunResult<User> runResult = new RunResult<User>();
            try
            {
                DataBase.Entity.User dbUser = AutoMapper.Mapper.Map<User, DataBase.Entity.User>(user);
                if (string.IsNullOrEmpty(user.Account) || string.IsNullOrEmpty(user.UserName))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "账号或者用户名为空";
                }
                else if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Account == dbUser.Account)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "账户已存在";
                }
                else if (!string.IsNullOrEmpty(user.Mobile) && _userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => !u.IsCasual && u.Mobile == dbUser.Mobile)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "手机号已存在";
                }
                else if (!string.IsNullOrEmpty(user.Email) && _userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => !u.IsCasual && u.Email == dbUser.Email)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "邮箱已存在";
                }
                else
                {
                    dbUser.ID = Guid.NewGuid();
                    dbUser.IsLock = false;
                    dbUser.LastLogin = 0;
                    dbUser.PassWord = dbUser.PassWord;
                    _userRepository.Add(dbUser);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        user.ID = dbUser.ID;
                        runResult.Status = ResultStatus.Success;
                        runResult.Result = AutoMapper.Mapper.Map<DataBase.Entity.User, User>(dbUser);
                        runResult.Message = "账户添加成功";
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "账户添加数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("账户添加出现异常,参数:" + JsonConvert.SerializeObject(user), exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "账户添加出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 修改用户,匿名用户无法修改
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public RunResult<User> Modify(User user)
        {
            RunResult<User> runResult = new RunResult<User>();
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == user.ID)))
                {
                    DataBase.Entity.User dbUser = _userRepository.GetByKey(user.ID);
                    dbUser.UserName = user.UserName;
                    dbUser.Qq = user.Qq;
                    _userRepository.Update(dbUser);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                        runResult.Result = user;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户信息修改数据库操作失败";
                    }
                }
                else
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在,用户编号为:" + user.ID;
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户信息修改数出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户信息修改数出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 用户登录，错误累积5次锁定用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public RunResult<bool> Login(User user)
        {
            RunResult<bool> runResult = new RunResult<bool>
            {
                Status = ResultStatus.Abnormal,
                Result = false
            };
            try
            {
                if (!_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Account == user.Account)))
                {
                    return new RunResult<bool>
                    {
                        Status = ResultStatus.Failure,
                        Result = false,
                        Message = string.Format("账户\"{0}\"不存在", user.Account)
                    };
                }
                DataBase.Entity.User dbUser = _userRepository.Get(Specification<DataBase.Entity.User>.Eval(u => u.Account == user.Account));
                if (dbUser.IsCasual)
                {
                    return new RunResult<bool>
                    {
                        Status = ResultStatus.Failure,
                        Message = "匿名账户无法登录",
                        Result = false
                    };
                }
                if (dbUser.IsLock)
                {
                    return new RunResult<bool>
                    {
                        Result = false,
                        Status = ResultStatus.Failure,
                        Message = "账户已经锁定",
               
                    };
                }
                if (dbUser.PassWord == user.PassWord)
                {
                    return new RunResult<bool>
                    {
                        Status = ResultStatus.Success,
                        Message = "登录成功",
                        Result = true
                    };
                }
                return new RunResult<bool>
                {
                    Status = ResultStatus.Failure,
                    Message = "密码错误",
                    Result = false
                };
            }
            catch (Exception exception)
            {
                Log.Error("账户登录出现异常,参数:" + JsonConvert.SerializeObject(user), exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "账户登录出现异常";
            }
            return runResult;
        }

        /// <summary>
        /// 修改手机号
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult ModifyMobile(Guid guid, string value)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Mobile == value && u.ID != guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该手机号已被其他用户使用";
                }
                else
                {
                    _userRepository.Update(guid, u => u.Mobile, value);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户手机号修改数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户手机号修改出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户手机号修改出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 修改邮箱
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult ModifyEmail(Guid guid, string value)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Email == value && u.ID != guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该邮箱已被其他用户使用";
                }
                else
                {
                    _userRepository.Update(guid, u => u.Email, value);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户邮箱修改数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户邮箱修改出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户邮箱修改出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult ModifyPassWord(Guid guid, string value)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (!_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在";
                }
                else
                {
                    _userRepository.Update(guid, u => u.PassWord, value);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户密码修改数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户密码修改出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户密码修改出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 修改最后登录时间
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RunResult ModifyLastLoginDate(Guid guid)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (!_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在";
                }
                else
                {
                    _userRepository.Update(guid, u => u.LastLogin, DateTime.Now.Ticks);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户最后登录修改数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户最后登录出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户最后登录出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RunResult<User> Get(Guid guid)
        {
            RunResult<User> runResult = new RunResult<User>();
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid)))
                {
                    DataBase.Entity.User dbUser = _userRepository.Get(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid));
                    runResult.Status = ResultStatus.Success;
                    runResult.Result = AutoMapper.Mapper.Map<DataBase.Entity.User, User>(dbUser);
                }
                else
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在";
                }

            }
            catch (Exception exception)
            {
                Log.Error("获取用户信息出现异常,该编号为:" + guid, exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "获取用户信息出现异常,该编号为:" + guid;
                runResult.Exception = exception;
            }
            return runResult;
        }

        public RunResult<User> Get(string account)
        {
            RunResult<User> runResult = new RunResult<User>();
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Account == account)))
                {
                    DataBase.Entity.User dbUser = _userRepository.Get(Specification<DataBase.Entity.User>.Eval(u => u.Account == account));
                    runResult.Status = ResultStatus.Success;
                    runResult.Result = AutoMapper.Mapper.Map<DataBase.Entity.User, User>(dbUser);
                }
                else
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户不存在";
                }
            }
            catch (Exception exception)
            {
                Log.Error(string.Format("获取用户信息出现异常,该账号为:{0}", account), exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = string.Format("获取用户信息出现异常,该账号为:{0}", account);
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 修改错误次数
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult ModifyErrorCount(Guid guid, int value)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (!_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在";
                }
                else
                {
                    _userRepository.Update(guid, u => u.ErrorCount, value);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户登录错误次数记录数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户登录错误次数修改出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户登录错误次数出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 锁定用户
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public RunResult LockUser(Guid guid)
        {
            RunResult runResult = new RunResult();
            try
            {
                if (!_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.ID == guid)))
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "该用户编号不存在";
                }
                else
                {
                    _userRepository.Update(guid, u => u.IsLock, true);
                    int r = RepositoryContext.Commit();
                    if (r > 0)
                    {
                        runResult.Status = ResultStatus.Success;
                    }
                    else
                    {
                        runResult.Status = ResultStatus.Failure;
                        runResult.Message = "用户锁定数据库操作失败";
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("用户锁定修改出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "用户锁定修改出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        /// <summary>
        /// 验证账户是否存在
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult<bool> ExistAccount(string value)
        {
            try
            {
                if (_userRepository.Exists(Specification<DataBase.Entity.User>.Eval(u => u.Account == value)))
                {
                    return new RunResult<bool>
                    {
                        Status = ResultStatus.Success,
                        Result = false

                    };
                }
                return new RunResult<bool>
                           {
                               Status = ResultStatus.Success,
                               Result = true
                           };
            }
            catch (Exception exception)
            {
                return new RunResult<bool>
                {
                    Exception = exception,
                    Status = ResultStatus.Abnormal,
                    Message = "验证账户出现异常"
                };
            }

        }

        /// <summary>
        /// 获取用户状态
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public RunResult<User> GetLoginStatus(string value)
        {
            try
            {
                var accont = _userRepository.Find(Specification<DataBase.Entity.User>.Eval(u => u.Account == value));
                if (accont == null)
                    return new RunResult<User>
                    {
                        Status = ResultStatus.Success,
                        Result = null
                    };
                return new RunResult<User>
                {
                    Status = ResultStatus.Success,
                    Result = new User
                    {
                        ErrorCount = accont.ErrorCount,
                        IsLock = accont.IsLock
                    }
                };
            }
            catch (Exception exception)
            {
                Log.Error("获取账户错误记录数,出现异常", exception);
                return new RunResult<User>
                {
                    Exception = exception,
                    Message = "获取账户错误记录数,出现异常",
                    Status = ResultStatus.Abnormal,
                    Result = null
                };
            }

        }
    }
}
